//渲染
async function render1() {
  document.querySelector("#kh").querySelector("img").src = `http://127.0.0.1:3000${localStorage.getItem("url")}`
  //渲染分类
  const res = await axios({
    url: '/category'
  })
  if (!res.code) {
    const str = res.msg.map(item => `
        <div data-id="${item.theme_id}" class="category-card bg-white rounded-xl shadow-md hover:shadow-lg transition-shadow duration-300 overflow-hidden">
              <img src="http://127.0.0.1:3000${item.theme_image}" class="w-full h-20 object-cover" alt="山水">
              <div class="p-4">
                <h4 class="text-lg font-medium text-gray-900">${item.theme_name}</h4>
                <p class="text-sm text-gray-500 mt-1">${item.theme_description}</p>
              </div>
            </div>
        `).join("")
    document.querySelector("#categoryGrid").innerHTML = str
  }

  //跳转诗词分类页
  const categorycards = document.querySelectorAll('#categoryGrid .category-card')
  categorycards.forEach(card => {
    card.addEventListener('click', function () {
      const theme_id = this.getAttribute('data-id')
      const themes_name = this.querySelector('h4').textContent
      location.href = `../classify/index.html?theme_id=${theme_id}&themes_name=${themes_name}`
    })
  })

  //渲染排行榜
  const res2 = await axios({
    url: '/activeUser'
  })
  const phb = document.querySelector('#sgph')
  if (res2.code == 0) {
    const str1 = res2.msg.map(item => `
       <div
            class="bg-gradient-to-br from-primary/10 via-primary/5 to-white p-6 rounded-xl shadow-md hover:shadow-lg transition-all duration-300 border border-primary/10">
            <div class="flex items-center space-x-4 mb-4">
              <span class="text-4xl font-bold text-primary">${item.ranking}</span>
              <img src="http://127.0.0.1:3000${item.avatar_url}"
                class="w-12 h-12 rounded-full" alt="用户头像">
              <div>
                <h4 class="font-medium text-gray-900">${item.nickname}</h4>
                <p class="text-sm text-gray-500">创作 ${item.poem_count} 首</p>
              </div>
            </div>
            <p class="text-gray-600 text-sm">${item.user_description}</p>
          </div>
      `).join("")
    phb.innerHTML = str1
  }
}
render1()


//清理文本
function addBrToText(text) {
  const pattern = /([，。！？\s])/g;
  return text.replace(pattern, '$1<br>');
}

//渲染每日推荐
async function render2() {
  const user_id = localStorage.getItem('user_id');
  const res1 = await axios({
    url: '/getrecom',
    params: { user_id }
  })
  const mrjx = document.querySelector('#mrjx')
  if (res1.code == 0) {
    console.log(res1.msg);

    const str = res1.msg.map(item => {
      return `
        <div class="bg-white rounded-lg shadow-sm overflow-hidden" data-id=${item.poem_id}>
                <img src="./asset/homesickness.jpg" class="w-full h-48 object-cover" alt="精选诗词">
                <div class="p-6">
                  <h4 class="text-lg font-medium text-gray-900 mb-2">${item.title}</h4>
                  <p class="text-gray-600 mb-4">${addBrToText(item.content)}</p >
    <div class="flex items-center justify-between">
      <div class="flex items-center space-x-2">
        <img src="http://127.0.0.1:3000${item.avatar_url}" class="w-8 h-8 rounded-full" alt="作者头像">
          <span class="text-sm text-gray-600">${item.nickname}</span>
      </div>
      <div class="flex items-center space-x-4">
        <button class="dz btn1 text-gray-400 hover:text-primary">
          <i class="dz iconfont icon-aixin ${item.is_liked == 1 ? 'red' : ""}"></i>
        <span class="dz ml-1">${item.likes_count}</span>
      </button>
      <button class="text-gray-400 hover:text-primary">
        <i class="far fa-comment"></i>
        <span class="ml-1">${item.comments_count}</span>
      </button>
    </div>
                  </div >
                </div >
              </div >
    `}).join("")
    mrjx.innerHTML = str
    mrjx.querySelectorAll(".btn1").forEach(button => {
      button.addEventListener('click', async function () {
        const poem_id = this.parentNode.parentNode.parentNode.parentNode.getAttribute('data-id')
        const res3 = await axios({
          url: '/toggleLike',
          method: 'POST',
          data: { poem_id, user_id }
        });
        if (res3.code == 0) {
          render2()
        }
      })
    })
    mrjx.querySelectorAll('.bg-white').forEach(item => {
      item.addEventListener('click', function (e) {
        if (!e.target.classList.contains('dz')) {
          const poem_id = this.getAttribute('data-id')
          const idd = 6
          location.href = `../detail/index.html?poem_id=${poem_id}&kh=${idd}} `;
        }
      })
    })
  }
}
render2()

//开始创作跳转ai创作
const btn = document.querySelector('.hero-section button');
btn.addEventListener('click', () => {
  location.href = '../aicreate/index.html'
})

//飞花令电梯导航跳转
const fhl = document.querySelector('.space-x-6 a:nth-child(2)');
fhl.addEventListener('click', function (e) {
  e.preventDefault();
  const top = document.querySelector('#features').offsetTop;
  document.documentElement.scrollTop = top;
})

//排行榜电梯导航跳转
const phb = document.querySelector('.space-x-6 a:nth-child(3)');
phb.addEventListener('click', function (e) {
  e.preventDefault();
  const top = document.querySelector('#a').offsetTop;
  document.documentElement.scrollTop = top;
})

const db = document.querySelector('.space-x-6 a:nth-child(4)');
window.addEventListener('scroll', function () {
  const top = document.documentElement.scrollTop;
  if (top > 500) {
    db.style.display = 'block';
  } else {
    db.style.display = 'none';
  }
})

//分类展开收起
const categoryGrid = document.querySelector("#zk")
const btnn = categoryGrid.querySelector('button');
let i = 1
btnn.addEventListener('click', function (event) {
  const grid = document.getElementById('categoryGrid');
  const button = event.currentTarget;
  const expanded = button.getAttribute('data-expanded') === 'true';
  if (i == 1) {
    categoryGrid.style.height = '700px';
    this.setAttribute('data-expanded', 'true');
    this.querySelector('span').textContent = '收起分类';
    i = 0
  } else {
    categoryGrid.style.height = '388px';
    this.setAttribute('data-expanded', 'false');
    this.querySelector('span').textContent = '查看更多分类';
    i = 1
  }
})




const tox = document.querySelector('#tox');
const btntx = document.querySelector('#tx');
const gr = document.querySelector('#tox a:nth-child(1)');
const tc = document.querySelector('#tox a:nth-child(3)');

// 定义节流时间（毫秒）

// 为 mouseenter 事件添加节流
const showTox = (function () {
  tox.style.display = 'block';
});
btntx.addEventListener('mouseenter', showTox);

// 为 mouseleave 事件添加防抖
const hideTox = _.debounce(function () {
  setTimeout(function () {
    tox.style.display = 'none';
  }, 4000);
}, 1000);
btntx.addEventListener('mouseleave', hideTox);

gr.addEventListener('click', function () {
  location.href = '../user/index.html';
});

tc.addEventListener('click', function () {
  location.href = '../login/index.html';
})

//飞花令
!(() => {
  let n
  const text = document.querySelector('.fhlp [type="text"]');
  const ii = document.querySelector('.fhlp i');

  const easyWords = ["月", "花", "酒", "水", "云", "山", "风", "雨", "春", "秋", "雪", "夜", "梦", "星", "柳", "雁", "香", "草", "霜", "露"];    // 随机选择一个词语
  const btn = document.querySelectorAll('.fhlp button');
  function defeat(text) {
    myAlert(true, `${text}, 游戏结束`)
    clearInterval(n)
    document.querySelector('.fhl').innerHTML = `剩余时间: 30 秒`
    btn[0].innerHTML = "开始游戏"
    btn[1].disabled = false;
  }
  btn[0].addEventListener('click', async function () {
    if (this.innerHTML === "提交") {
      if (text.value.trim() == "") {
        myAlert(true, '请输入内容')
        return
      }
      const res = await axios({
        url: '/searchfhl',
        params: {
          keyword: document.querySelector('#keyword').innerHTML,
          content: text.value
        }
      })
      if (res.code == 0) ii.style.display = 'inline-block'
      if (res.code == 0 && res.msg == 2) {
        ii.classList.add("cuo")
        ii.classList.remove('icon-duicuo-yuan-dui')
        ii.style.display = 'inline-block'
        defeat("回答错误")
      }
      setTimeout(() => {
        ii.style.display = 'none'
        text.value = ""
      }, 1000)
      if (res.code == 0 && res.msg == 2) return
      ii.className = "iconfont icon-duicuo-yuan-dui icon-duicuo-yuan-cuo"
      clearInterval(n)
    } else {
      btn[1].disabled = true;
      this.innerHTML = "提交"
    }
    document.querySelector('.fhl').innerHTML = `剩余时间: 30 秒`
    let i = 30
    n = setInterval(function () {
      i--
      if (i == 0) {
        defeat("时间结束")
        return
      }
      document.querySelector('.fhl').innerHTML = `剩余时间: ${i} 秒`
    }, 1000)
  })
  btn[1].addEventListener('click', function () {
    document.querySelector('#keyword').innerHTML = easyWords[Math.floor(Math.random() * easyWords.length)];
  })
})()

//搜索框

// 初始化时强制清空
const searchInput = document.getElementById('searchInput');
searchInput.value = ''; // 确保初始值为空

// 破解浏览器自动填充机制
const randomId = 'input-' + Math.random().toString(36).substr(2, 5);
searchInput.setAttribute('name', randomId);
searchInput.setAttribute('id', randomId);
const searchResults = document.getElementById('searchResults');
let timeoutId;

// 防抖函数（300ms）
function debounce(func, delay) {
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, args), delay);
  };
}

// 获取搜索结果
async function fetchResults(searchTerm) {
  try {
    // 添加加载状态
    searchResults.innerHTML = '<div class="result-item">搜索中...</div>';
    searchResults.style.display = 'block';

    const response = await fetch(
      `http://127.0.0.1:3000/api/getPoemsid?keyword=${encodeURIComponent(searchTerm)}`
    );

    if (!response.ok) throw new Error(`请求失败: ${response.status}`);

    const data = await response.json();

    searchResults.innerHTML = '';
    if (data.msg.length > 0) {
      data.msg.forEach(item => {
        const div = document.createElement('div');
        div.className = 'result-item';
        div.textContent = item.title || item; // 根据实际数据结构调整
        div.onclick = () => {
          // 点击结果项时，跳转到对应的页面
          location.href = `../detail/index.html?poem_id=${item.poem_id}`
          searchResults.style.display = 'none';
        };
        searchResults.appendChild(div);
      });
    } else {
      searchResults.innerHTML = '<div class="result-item">无结果</div>';
    }
  } catch (error) {
    console.error('搜索出错:', error);
    searchResults.innerHTML = `<div class="result-item error">${error.message}</div>`;
  }
}

// 添加事件监听（关键修复！）
const debouncedSearch = debounce((term) => {
  if (term.length === 0) {
    searchResults.style.display = 'none';
    return;
  }
  fetchResults(term);
}, 700);

// 绑定输入事件
searchInput.addEventListener('input', (e) => {
  debouncedSearch(e.target.value.trim());
});

// 点击外部关闭
document.addEventListener('click', (e) => {
  if (!e.target.closest('.search-container')) {
    searchResults.style.display = 'none';
  }
});

// 初始隐藏结果框（关键修复！）
searchResults.style.display = 'none';

const xxx2 = document.querySelector('#xxx2')
xxx2.addEventListener('click', function (e) {
  if (e.target.tagName == 'BUTTON') {
    alert('功能还未开放')
  }
})
